<template>
  <ECharts class="chart" :option="option" />
</template>

<script setup>
import ECharts from 'vue-echarts'
import { ref, computed, onMounted } from 'vue'
import { getBehavioralTraitList } from '@/api/flaud/behavioraltrait'
import * as echarts from 'echarts' 

const page = ref(0)
const total = ref(0)
const pageSize = ref(0)
const tableData = ref([])
const searchInfo = ref({})

onMounted(() => {
  getTableData()
})

const getTableData = async () => {
  const table = await getBehavioralTraitList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
    countOccupation()
  }
  console.log(tableData.value)
}

const mydata = ref([])

const countOccupation = () => {
  const countMap = {}
  tableData.value.forEach(item => {
    const occupation = item.occupation
    countMap[occupation] = (countMap[occupation] || 0) + 1
  })
  mydata.value = Object.entries(countMap).map(([name, value]) => ({
    name,
    value,
    score: 50 
  }))
}

const option = computed(() => {
  // 定义清晰的渐变（绿到蓝）
  const gradientColors = [
    { offset: 0, color: '#65B581' },   // 起始色（绿）
    { offset: 1, color: '#3A84FF' }    // 结束色（蓝）
  ]

  return {
    title: {
      text: '行为人特质',
      top: 10,
      left: 10,
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#333'
      }
    },
    dataset: {
      source: [
        ['score', 'value', 'category'],  
        ...mydata.value.map(item => [item.score, item.value, item.name])
      ]
    },
    grid: { 
      containLabel: true,
      left: '10%',
      right: '15%',
      bottom: '10%',
      top: '20%'
    },
    xAxis: { 
      name: '数量',
      type: 'value',
      nameTextStyle: {
        color: '#666',
        fontSize: 14
      },
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisTick: {
        show: false
      }
    },
    yAxis: {
      type: 'category',  
      name: '特质',
      nameTextStyle: {
        color: '#666',
        fontSize: 14
      },
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#666',
        fontSize: 13
      }
    },
    series: [
      {
        type: 'bar',
        encode: {
          x: 'value',  
          y: 'category'
        },
        label: {
          show: true,
          position: 'right',
          color: '#333',
          fontSize: 13
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, gradientColors),
          borderRadius: 4 
        }
      }
    ]
  }
})
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  background-color: #fff;
  margin: 20px 0;
}
</style>